package pers.vic.widget.automation.baidu.service;

import java.io.IOException;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;

import pers.vic.boot.base.craw.CrawlConnect;
import pers.vic.boot.util.JsonUtil;
import pers.vic.widget.automation.baidu.model.BaiduCookie;

/**
 * @author Vic.xu
 * @description:百度先关请求的基类 主要是为了统一加header
 * @date: 2021/7/21 0021 8:45
 */
public abstract class BaseBaiduService {

    protected Logger logger = LoggerFactory.getLogger(getClass().getSimpleName());

    protected static int timeOut = 50000;

    /**
     * 组装header
     * 
     * @param con
     * @param baiduCookie
     */
    private static void header(CrawlConnect con, BaiduCookie baiduCookie) {

        con.header("Cookie", baiduCookie.getCookie()).header("Accept", " */*")
            .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
            .header("Host", "tieba.baidu.com")
            .header("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
            .header("X-Requested-With", "XMLHttpRequest").header("Origin", "https://tieba.baidu.com")
            .header("Sec-Fetch-Mode", "cors").header("Referer", "https://tieba.baidu.com/index.html")
            .data("ie", "utf-8").data("tbs", baiduCookie.getSignTbs());
    }

    public static String DEFAULT_COOKIE = "";

    public static CrawlConnect con(String url, BaiduCookie baiduCookie) {
        Connection conn = Jsoup.connect(url).ignoreContentType(true).timeout(timeOut);
        CrawlConnect crawlConnect = new CrawlConnect(conn);
        header(crawlConnect, baiduCookie);
        return crawlConnect;
    }

    /**
     * 请求并返回 map
     * 
     * @param url
     * @param baiduCookie
     * @return
     * @throws IOException
     */
    public static Map<String, Object> requestForMap(String url, BaiduCookie baiduCookie) throws IOException {
        CrawlConnect con = con(url, baiduCookie);
        String html = con.postBodyText();
        Map<String, Object> map = JsonUtil.jsonToObject(html, new TypeReference<Map<String, Object>>() {});
        return map;
    }

}
